import mysql from 'mysql';

export default function(params = {}) {
	/**
	 * SQL: 执行的sql语句，参数拼接后的
	 */
	const { SQL, resolve, reject } = params;
	try {
		// 建立连接池
		const pools = mysql.createPool({
			//host: '149.129.105.147',
			host: '127.0.0.1',
			password: '123456',
			port: '3306',
			// database: 'yudada_test',
			database: 'activity_test',
			// user: 'yudada_test'
			user: 'root',
			connectionLimit: 10
		});
		// 调用其中一个连接
		pools.getConnection((poolErr, conn) => {
			if (poolErr) {
				reject({ code: -1, message: poolErr });
				return;
			}
			// 加入事务机制
			// conn.beginTransaction(error => {
				// 查询语句
				conn.query(SQL, (err, result) => {
					console.log(
						`connect---console:::SQL:${SQL}--data:::${JSON.stringify(
							result
						)}--error:::${err}`
					);
					if (err) {
						reject({ code: -1, message: err });
						// 出错回滚
						// conn.rollback();
						console.log(`query:-${SQL}`, err.message);
					} else {
						resolve({ code: 1, data: result });
					}
					// 释放连接
					conn.release();
				});
			// });
		});
	} catch (err) {
		reject({ code: -1, message: err });
		console.log(err);
	}
}
